package com.ksyun.campus.dataserver.services;

import com.alibaba.fastjson.JSONObject;
import com.ksyun.campus.dataserver.config.dataserverconfig.DataServerConfigProperties;
import com.ksyun.campus.dataserver.domain.DataServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DataServerUpdateService /*implements ApplicationRunner*/ {
    @Resource
    private ZkClient zkClient;

    @Autowired
    DataServerConfigProperties dataServerConfigProperties;

    @Autowired
    private Map<String, DataServerInfo> dataServerInfoMap;

    @Autowired
    DataServerInfo dataServerInfo;

//    @Override
//    public void run(ApplicationArguments args) throws Exception {
//        updateDsServerMap();
//        UpdataCurrentServerInfo();
//        log.debug("节点列表为：{}", dataServerInfoMap);
//        log.debug("当前服务信息为：{}", dataServerInfoMap.get("node1"));
//    }

//    @Scheduled(cron = "0/1 * * * * ?")
    public void update(){
//        updateDsServerMap();
//        UpdataCurrentServerInfo();
        log.debug("节点列表为：{}", dataServerInfoMap);
        log.debug("当前服务信息为：{}", dataServerInfo);

    }
    private void updateDsServerMap() {
        //创建子节点变化监听器
        IZkChildListener childListener = new IZkChildListener() {
            /**
             *子节点变化事件回调方法
             * @param s  节点路径
             * @param list  变化后的子节点列表
             */
            @Override
            public void handleChildChange(String s, List<String> list) {
                log.info(s + "下的子节点更新为{}", list);
                dataServerInfoMap.clear();
                for (String node: list) {
                    String dataServerInfoJsonStr = (String) zkClient.readData(dataServerConfigProperties.getRootName()+"/"+node);
                    log.info("updateDsServerMap: {}",dataServerInfoJsonStr);
                    DataServerInfo server = JSONObject.parseObject(dataServerInfoJsonStr,DataServerInfo.class);
                    dataServerInfoMap.put(node, server);
                }
            }

        };
        // 监听dataserver根节点下的子节点
        zkClient.subscribeChildChanges(dataServerConfigProperties.getRootName(), childListener);
    }

    private void UpdataCurrentServerInfo(){
        zkClient.subscribeDataChanges(dataServerConfigProperties.getRootName(), new IZkDataListener() {
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("Node " + dataPath + " deleted.");
                dataServerInfoMap.remove(dataPath.replaceFirst(dataServerConfigProperties.getRootName(),""));
            }
            public void handleDataChange(String dataPath, Object data) throws Exception {
                String nodeName = dataPath.replaceFirst(dataServerConfigProperties.getRootName()+"/","");

                String dataServerInfoJsonStr = (String) data;
                System.out.println(data);
                DataServerInfo server = JSONObject.parseObject(dataServerInfoJsonStr,DataServerInfo.class);
                dataServerInfoMap.put(nodeName, server);
                System.out.println("Node " + dataPath + " changed, new data: " + data);
            }
        });

    }
}
